package com.ctg.itrdc.sysmgr.permission.core.sso;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.SessionException;
import org.apache.shiro.session.mgt.SessionManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.servlet.AdviceFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class CasLogoutFilter extends AdviceFilter{
    private static final Logger log = LoggerFactory.getLogger(CasLogoutFilter.class);
    private SingleSignOutHandler HANDLER;

    private SessionManager sessionManager;

    public void setSessionManager(SessionManager sessionManager) {
        this.sessionManager = sessionManager;
    }
    
    public void setSignOutHandler(SingleSignOutHandler handler) {
    	HANDLER = handler;
    }
    
    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest req = (HttpServletRequest)request;
        if (HANDLER.isTokenRequest((HttpServletRequest)req)) {
            HANDLER.recordSubject(req);
            return true;
        } else if (HANDLER.isLogoutRequest(req)) {
            HANDLER.invalidateSession(req,sessionManager);
            // Do not continue up filter chain
            return false;
        } else {
            log.trace("Ignoring URI " + req.getRequestURI());
        }
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession(false);
        if (session!=null&&session.getAttribute(HANDLER.getLogoutParameterName())!=null) {
            try {
                subject.logout();
            } catch (SessionException ise) {
                log.debug("Encountered session exception during logout.  This can generally safely be ignored.", ise);
            }
        }
        return true;
    }
    
}
